package com.hsnn.medstgmini.base.dict.dao.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.base.dict.dao.DicDrugformLogDao;
import com.hsnn.medstgmini.base.dict.model.DicDrugformLog;
import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.util.Pagination;

/**
 * 基础库 数据字典 剂型字典 维护记录接口实现类
 * 
 * @author hssdzxssh
 *
 */
@Repository
public class DicDrugformLogDaoImpl extends BaseHibernateDAO implements  DicDrugformLogDao {
	
	@Resource(name = "sessionFactory")
	private SessionFactory factory;
	
	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;
	
	@Autowired
	private HibernateSqlUtil sqlUtil;
	
	/**
	 * 基础库 数据字典 剂型字典 维护记录添加
	 * 
	 * @param dicDrugformLog
	 */
	@Override
	public boolean add(DicDrugformLog dicDrugformLog) {
			getSession().clear();
			this.getSession().saveOrUpdate(dicDrugformLog);
			getSession().flush();
			return true;
	}

	/**
	 * 基础库 数据字典 剂型字典 维护记录查询所有及条件查询
	 * 
	 * @param dicDrugformLog
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<DicDrugformLog> queryDicDrugformLogByName(Pagination page,
			DicDrugformLog dicDrugformLog) {
		String formId = dicDrugformLog.getFormId();
		String date1 = dicDrugformLog.getFormCode();
		String date2 = dicDrugformLog.getFormName();
		StringBuffer hql = new StringBuffer();
		StringBuffer hqlCount = new StringBuffer();
		hqlCount.append(" select count(*) from DicDrugformLog where form_id = ? ");
		hql.append(" from DicDrugformLog where form_id = ? ");
		if (null != date1 && !("").equals(date1)) {
			hqlCount.append(" and upd_datetime > ?");
			hql.append(" and upd_datetime > ?");
		} else if (null != date1 && !("").equals(date1)) {
			hqlCount.append(" and upd_datetime < ? ");
			hql.append(" and upd_datetime < ? ");
		} else if (null != date1 && !("").equals(date1)
				&& (null != date2 && !("").equals(date2))) {
			hqlCount.append(" and (upd_datetime between  ? and  ? )");
			hql.append(" and (upd_datetime between  ? and  ? )");
		}
		hql.append(" order by upd_datetime ");
		Query query = getSession().createQuery(hql.toString());
		Query queryCount = getSession().createQuery(hqlCount.toString());
		query.setParameter(0, formId);
		queryCount.setParameter(0, formId);
		if (null != date1 && !("").equals(date1)) {
			query.setParameter(1, date1);
			queryCount.setParameter(1, date1);
		} else if (null != date2 && !("").equals(date2)) {
			query.setParameter(1, date2);
			queryCount.setParameter(1, date2);
		} else if (null != date1 && !("").equals(date1)
				&& (null != date2 && !("").equals(date2))) {
			query.setParameter(1, date1);
			query.setParameter(2, date2);
			queryCount.setParameter(1, date1);
			queryCount.setParameter(2, date2);
		}
		dicDrugformLog.setCount(Long.valueOf(queryCount.list().get(0)+""));
		query.setFirstResult((page.getPage()-1)*page.getMaxResults());
		query.setMaxResults(page.getMaxResults());
		return query.list();
		
	}

	/**
	 * 维护记录
	 */
	@Override
	public Pagination queryDicDrugformLogList(Pagination page) {
		String date1 = page.getConditions().get("date1");
		String date2 = page.getConditions().get("date2");
		String formId = page.getConditions().get("formId");
		String formCode =page.getConditions().get("formCode");
		StringBuffer sql1 = new StringBuffer();
		sql1.append("	    SELECT a.form_code father_form_code,a.form_name father_form_name,NULL m,NULL n,a.detail detail,a.status,    ")
			.append("		s.name,a.upd_datetime,a.log_id logId FROM  dic_drugform_log a     ")
			.append("	     LEFT JOIN sys_user s ON s.id=a.upd_user               ")
			.append("       WHERE a.form_id=:formId                                ");
		StringBuffer sql2 = new StringBuffer();
		sql2.append("SELECT a.form_code father_form_code,a.form_name father_form_name,b.form_code,b.form_name,b.detail,       ")
		    .append(" b.status,s.name,b.upd_datetime,b.log_id logId FROM  dic_drugform_log b  ")
		    .append(" left JOIN dic_drugform a ON a.form_id=b.father_id           ")
		    .append(" LEFT JOIN sys_user s ON s.id=b.upd_user                      ")
		    .append(" WHERE b.form_id=:formId                                      ");
		StringBuffer sqlCount1 = new StringBuffer();
		sqlCount1.append("SELECT COUNT(*) FROM dic_drugform_log a ")
		         .append(" WHERE form_id=:formId ");
		StringBuffer sqlCount2 = new StringBuffer();
		sqlCount2.append("SELECT COUNT(*) FROM dic_drugform_log b   ")
		         .append(" left JOIN dic_drugform a ON a.form_id=b.father_id  ")
		         .append(" WHERE b.form_id=:formId ");
		if(StringUtils.isNotBlank(formCode)){
			if(StringUtils.isNotBlank(date1)){
				sql2.append(" and b.upd_datetime >= :date1 ");
				sqlCount2.append(" and b.upd_datetime >= :date1 ");
			}
			if(StringUtils.isNotBlank(date2)){
				sql2.append(" and b.upd_datetime <= :date2 ");
				sqlCount2.append(" and b.upd_datetime <= :date2 ");
			}
			sql2.append(" order by b.upd_datetime desc");
			Query query = getSession().createSQLQuery(sql2.toString());
			Query queryCount = getSession().createSQLQuery(sqlCount2.toString());
			query.setString("formId", formId);
			queryCount.setString("formId", formId);
			if(StringUtils.isNotBlank(date1)){
				query.setString("date1", date1+" 00:00:00");
				queryCount.setString("date1", date1+" 00:00:00");
			}
			if(StringUtils.isNotBlank(date2)){
				query.setString("date2", date2+" 23:59:59");
				queryCount.setString("date2", date2+" 23:59:59");
			}
			page.setRecords(Long.parseLong(queryCount.uniqueResult().toString()));
			query.setFirstResult((page.getPage()-1)*page.getMaxResults());
			query.setMaxResults(page.getMaxResults());
			page.setRows(query.list());
			return page;
		}else{
			if(StringUtils.isNotBlank(date1)){
				sql1.append(" and a.upd_datetime >= :date1 ");
				sqlCount1.append(" and a.upd_datetime >= :date1 ");
			}
			if(StringUtils.isNotBlank(date2)){
				sql1.append(" and a.upd_datetime <= :date2 ");
				sqlCount1.append(" and a.upd_datetime <= :date2 ");
			}
			sql1.append(" order by a.upd_datetime desc");
			Query query = getSession().createSQLQuery(sql1.toString());
			Query queryCount = getSession().createSQLQuery(sqlCount1.toString());
			query.setString("formId", formId);
			queryCount.setString("formId", formId);
			if(StringUtils.isNotBlank(date1)){
				query.setString("date1", date1+" 00:00:00");
				queryCount.setString("date1", date1+" 00:00:00");
			}
			if(StringUtils.isNotBlank(date2)){
				query.setString("date2", date2+" 23:59:59");
				queryCount.setString("date2", date2+" 23:59:59");
			}
			page.setRecords(Long.parseLong(queryCount.uniqueResult().toString()));
			query.setFirstResult((page.getPage()-1)*page.getMaxResults());
			query.setMaxResults(page.getMaxResults());
			page.setRows(query.list());
			return page;
		}
	}

	/**
	 * 基础库 数据字典 剂型字典维护记录
	 * @param page
	 * @return
	 */
    public Pagination getAllHis(Pagination page) {

    	String date1 = page.getConditions().get("date1");
		String date2 = page.getConditions().get("date2");
		String formId = page.getConditions().get("formId");
		String formCode =page.getConditions().get("formCode");
		StringBuffer sql1 = new StringBuffer();
		sql1.append("	    SELECT a.form_code father_form_code,a.form_name father_form_name,NULL m,NULL n,a.status,    ")
			.append("		s.name,a.upd_datetime,a.log_id logId FROM  dic_drugform_log a     ")
			.append("	     LEFT JOIN sys_user s ON s.id=a.upd_user               ")
			.append("       WHERE a.form_id=:formId                                ");
		StringBuffer sql2 = new StringBuffer();
		sql2.append("SELECT a.form_code father_form_code,a.form_name father_form_name,b.form_code,b.form_name,       ")
		    .append(" b.status,s.name,b.upd_datetime,b.log_id logId FROM  dic_drugform_log b  ")
		    .append(" INNER JOIN dic_drugform a ON a.form_id=b.father_id           ")
		    .append(" LEFT JOIN sys_user s ON s.id=b.upd_user                      ")
		    .append(" WHERE b.form_id=:formId                                      ");
		StringBuffer sqlCount1 = new StringBuffer();
		sqlCount1.append("SELECT COUNT(*) FROM dic_drugform_log a ")
		         .append(" WHERE form_id=:formId ");
		StringBuffer sqlCount2 = new StringBuffer();
		sqlCount2.append("SELECT COUNT(*) FROM dic_drugform_log b   ")
		         .append(" INNER JOIN dic_drugform a ON a.form_id=b.father_id  ")
		         .append(" WHERE b.form_id=:formId ");
		if(StringUtils.isNotBlank(formCode)){
			if(StringUtils.isNotBlank(date1)){
				sql2.append(" and b.upd_datetime >= :date1 ");
				sqlCount2.append(" and b.upd_datetime >= :date1 ");
			}
			if(StringUtils.isNotBlank(date2)){
				sql2.append(" and b.upd_datetime <= :date2 ");
				sqlCount2.append(" and b.upd_datetime <= :date2 ");
			}
			sql2.append(" order by b.upd_datetime desc");
			Query query = getSession().createSQLQuery(sql2.toString());
			Query queryCount = getSession().createSQLQuery(sqlCount2.toString());
			query.setString("formId", formId);
			queryCount.setString("formId", formId);
			if(StringUtils.isNotBlank(date1)){
				query.setString("date1", date1+" 00:00:00");
				queryCount.setString("date1", date1+" 00:00:00");
			}
			if(StringUtils.isNotBlank(date2)){
				query.setString("date2", date2+" 23:59:59");
				queryCount.setString("date2", date2+" 23:59:59");
			}
			page.setRecords(Long.parseLong(queryCount.uniqueResult().toString()));
			query.setFirstResult((page.getPage()-1)*page.getMaxResults());
			query.setMaxResults(page.getMaxResults());
			page.setRows(query.list());
			return page;
		}else{
			if(StringUtils.isNotBlank(date1)){
				sql1.append(" and a.upd_datetime >= :date1 ");
				sqlCount1.append(" and a.upd_datetime >= :date1 ");
			}
			if(StringUtils.isNotBlank(date2)){
				sql1.append(" and a.upd_datetime <= :date2 ");
				sqlCount1.append(" and a.upd_datetime <= :date2 ");
			}
			sql1.append(" order by a.upd_datetime desc");
			Query query = getSession().createSQLQuery(sql1.toString());
			Query queryCount = getSession().createSQLQuery(sqlCount1.toString());
			query.setString("formId", formId);
			queryCount.setString("formId", formId);
			if(StringUtils.isNotBlank(date1)){
				query.setString("date1", date1+" 00:00:00");
				queryCount.setString("date1", date1+" 00:00:00");
			}
			if(StringUtils.isNotBlank(date2)){
				query.setString("date2", date2+" 23:59:59");
				queryCount.setString("date2", date2+" 23:59:59");
			}
			page.setRecords(Long.parseLong(queryCount.uniqueResult().toString()));
			query.setFirstResult((page.getPage()-1)*page.getMaxResults());
			query.setMaxResults(page.getMaxResults());
			page.setRows(query.list());
			return page;
		}
    }

    /**
     * 前后对比
     */
	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> getDicDrugformLogDetail(Pagination page) {
		Session session = sessionFactory.getCurrentSession();
		String logId = page.getConditions().get("logId");
		StringBuffer  sql = new StringBuffer();
		sql.append(" SELECT case when b.father_id = '0' then b.form_code else a.form_code end fatherFormCode,  ")
		   .append(" case when b.father_id = '0' then b.form_name else a.form_name end fatherFormName, ")
		   .append(" case when b.father_id = '0' then null else b.form_code end formCode,")
		   .append(" case when b.father_id = '0' then null else b.form_name end formName,b.status status,b.log_id logId , ")
		   .append(" date_format(b.upd_datetime,'%Y-%m-%d %T') updDatetime,s.name name FROM  dic_drugform_log b ")
		   .append(" LEFT JOIN dic_drugform a ON a.form_id=b.father_id  LEFT JOIN sys_user s ON s.id=b.upd_user ")
		   .append(" WHERE b.form_id = (SELECT form_id FROM dic_drugform_log WHERE log_id = :logId) ")
		   .append(" AND b.upd_datetime <= (SELECT upd_datetime FROM dic_drugform_log where log_id = :logId) ")
		   .append(" order by b.upd_datetime desc limit 2 ");
		Query query = session.createSQLQuery(sql.toString());
		query.setString("logId", logId);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		return query.list();
	}
}